package com.sgj.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: Guoji Shen
 * @Date: 2021/8/5 9:11
 */
public class ThreadDemo2 {

    public static void main(String[] args) {
        Share share = new Share();

        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                share.incr();
            }
        }, "AA").start();

        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                share.decr();
            }
        }, "BB").start();
    }
}

class Share {
    // 初始值
    private int number;

    // 创建Lock
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    // +1的方法
    public void incr() {
        // 上锁
        lock.lock();
        try {
            // 判断number是否为0，如果不是0，等待
            while(number != 0) {
                condition.await();
            }
            // 如果number为0，+1
            number ++;
            System.out.println(Thread.currentThread().getName() + " :: " + number);
            // 通知其他线程
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 解锁
            lock.unlock();
        }
    }

    // -1的方法
    public void decr() {
        // 上锁
        lock.lock();
        try {
            // 判断number是否为1，如果不是1，等待
            while(number != 1) {
                condition.await();
            }
            // 如果number为1，-1
            number --;
            System.out.println(Thread.currentThread().getName() + " :: " + number);
            // 通知其他线程
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 解锁
            lock.unlock();
        }
    }
}